package com.lczyfz.istep.modules.openstack.api.glance.impl.parseJson;


import com.lczyfz.istep.modules.openstack.api.glance.model.Image;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * 用于封装和解析glance API 的相关参数JSON
 * @author jm
 */
public class GlanceParse {

	public static List<Image> resolveImages(JSONObject imagesJson){
		List<Image> imageList = new ArrayList<Image>();
		JSONArray images = imagesJson.getJSONArray("images");
		for(int i = 0 ; i < images.size(); i++){
			Image image = new Image();
			image.setId( images.getJSONObject(i).getString("id"));
			image.setName( images.getJSONObject(i).getString("name"));
			if(images.getJSONObject(i).getString("size") != null)
				image.setSize(images.getJSONObject(i).getString("size"));
			image.setStatus(images.getJSONObject(i).getString("status"));
			image.setCreatedTime(images.getJSONObject(i).getString("created_at"));
			image.setFilePath(images.getJSONObject(i).getString("file"));
			image.setOwener(images.getJSONObject(i).getString("owner"));
			image.setDiskFormat(images.getJSONObject(i).getString("disk_format"));
			imageList.add(image);
		}
		return imageList;
	}

	public static Image resolveImageById(JSONObject imageJson){
		Image image = new Image();
		image.setId( imageJson.getString("id"));
		image.setName( imageJson.getString("name"));
		image.setSize(imageJson.getString("size"));
		image.setStatus(imageJson.getString("status"));
		image.setCreatedTime(imageJson.getString("created_at"));
		image.setFilePath(imageJson.getString("file"));
		image.setOwener(imageJson.getString("owner"));
		image.setDiskFormat(imageJson.getString("disk_format"));
		image.setvisibility(imageJson.getString("visibility"));
		return image;
	}

	public static JSONObject packageCreatImage(Image image){

		JSONObject params = new JSONObject();
		if(image.getDiskFormat() != null){
			params.put("disk_format",image.getDiskFormat());
		}
		if(image.getName() != null){
			params.put("name", image.getName());
		}
		if(image.getvisibility() != null){
			params.put("visibility", image.getvisibility());
		}
		if(image.getContainerFormat() != null){
			params.put("container_format", image.getContainerFormat());
		}else{
			params.put("container_format", "bare");
		}
		if(image.getNicModel() != null){
			params.put("hw_vif_model", image.getNicModel());
		}else{
			params.put("hw_vif_model", "rtl8139");
		}

		return params;
	}

}
